package com.jht.bletool2kotlin.activity.homepage.fragment.device

import android.bluetooth.BluetoothAdapter
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.util.Log
import com.jht.bletool2kotlin.activity.homepage.fragment.device.bean.BLEDevice

private const val TAG = "DevicePresenter"

class DevicePresenter(private val deviceUi: IDevice.UI) : IDevice.Presenter {

    private val bleScanCallback = BleScanCallback()

    override fun startScanBle(btAdapter: BluetoothAdapter) {
        btAdapter.bluetoothLeScanner.startScan(bleScanCallback)
    }

    override fun stopScanBle(btAdapter: BluetoothAdapter) {
        btAdapter.bluetoothLeScanner.stopScan(bleScanCallback)
    }

    inner class BleScanCallback : ScanCallback() {

        override fun onScanResult(callbackType: Int, result: ScanResult?) {
            Log.d(TAG, "onScanResult: callbackType = $callbackType , result = ${result?.device?.name}")
            when (callbackType) {
                ScanSettings.CALLBACK_TYPE_ALL_MATCHES -> {
                    val bt = result?.let {
                        // val device: BluetoothDevice,var rssi:Int, var scanRecord:ByteArray
                        if (!it.device.name.isNullOrBlank()){
                            BLEDevice(it.device, it.rssi, it.scanRecord?.bytes ?: ByteArray(0))
                        }else{
                            null
                        }
                    }
                    deviceUi.addBleDevice(bt)
                }
            }
        }

        override fun onBatchScanResults(results: MutableList<ScanResult>?) {
            Log.d(TAG, "onBatchScanResults: $results")
        }

        override fun onScanFailed(errorCode: Int) {
            Log.e(TAG, "onScanFailed: errorCode = $errorCode")
        }
    }


}